﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web;
using System.Reflection;

namespace Headlight
{
    public class FormActionAttribute
        : ActionNameSelectorAttribute
    {
        public override bool IsValidName(
            ControllerContext controllerContext,
            string actionName,
            MethodInfo methodInfo)
        {
            return controllerContext.HttpContext.Request[Prefix + methodInfo.Name] != null
                && !controllerContext.IsChildAction;
        }

        public string Prefix = "Action_";
    }


    /// <summary>
    /// Used to vary an action method based on which button in a form was pressed. This
    /// is useful but is an anti-pattern because it couples the controller to names
    /// used in the form elements. 
    /// </summary>
    /// <remarks>
    /// See the example at http://weblogs.asp.net/dfindley/archive/2009/05/31/asp-net-mvc-multiple-buttons-in-the-same-form.aspx
    /// </remarks>
    public class AcceptButtonAttribute : ActionMethodSelectorAttribute
    {
        public string ButtonName { get; set; }

        public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
        {
            var req = controllerContext.RequestContext.HttpContext.Request;
            return !string.IsNullOrEmpty(req.Form[this.ButtonName]);
        }
    }
}